package com.kim.authorization.server.service;

import com.kim.authorization.server.dto.ClientsDTO;
import com.kim.authorization.server.mapper.ClientsMapper;
import com.kim.authorization.server.model.Clients;
import com.kim.oauth.common.constants.Oauth2ExceptionEnum;
import com.kim.common.utilcom.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Service;

/**
 * 客户端Service
 */
@Slf4j
@Service
public class MyBatisClientDetailsServiceImpl implements ClientDetailsService {

    /**
     * clientMapper
     */
    private final ClientsMapper clientsMapper;

    public MyBatisClientDetailsServiceImpl(ClientsMapper clientsMapper) {
        this.clientsMapper = clientsMapper;
    }

    /**
     * 查询客户端根据客户端ID
     *
     * @param clientId 客户端ID
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        if (clientId == null || clientId.trim().length() <= 0) {
            log.error(Oauth2ExceptionEnum.CLIENT_NOT_FOUND.getMsg());
            throw new ClientRegistrationException(Oauth2ExceptionEnum.CLIENT_NOT_FOUND.getMsg());
        }
        // 查询客户端根据客户端ID
        Clients clients = clientsMapper.selectById(clientId);
        if (clients != null) {
            return clients;
        }
        log.error(Oauth2ExceptionEnum.CLIENT_ID_EMPTY.getMsg());
        throw new ClientRegistrationException(Oauth2ExceptionEnum.CLIENT_ID_EMPTY.getMsg());
    }

    /**
     * 新增客户端
     *
     * @param clientsDto 客户端信息
     */
    public Object insert(ClientsDTO clientsDto) {
        String secret = clientsDto.getClientSecret();
        String secretEncode = new BCryptPasswordEncoder().encode(secret);
        clientsDto.setClientSecret(secretEncode);
        if (StringUtils.isBlank(clientsDto.getScope())) {
            clientsDto.setScope("all");
        }
        if (StringUtils.isBlank(clientsDto.getAuthorizedGrantTypes())) {
            clientsDto.setAuthorizedGrantTypes("authorization_code,password,refresh_token");
        }
        clientsMapper.insert(clientsDto);
        return Result.succeed("新增客户端成功");
    }
}

